#include "stdafx.h"
#include "BasicSimpleToolTip.h"
#include <CommCtrl.h>
#pragma comment(lib,"comctl32.lib")

namespace BasicSkinView
{


	CBasicSimpleToolTip::CBasicSimpleToolTip()
		:m_hTipWnd(NULL)
		,m_hFakeParent(NULL)
		,m_pCurrentHolder(NULL)
	{

	}

	CBasicSimpleToolTip::~CBasicSimpleToolTip()
	{
		Destroy();
	}

	BOOL CBasicSimpleToolTip::Create(HWND hParent)
	{
		INITCOMMONCONTROLSEX iccex;
		//INITIALIZE COMMON CONTROLS
		static bool s_bInitToolTip;
		if(!s_bInitToolTip)
		{
			s_bInitToolTip = true;
			iccex.dwICC = ICC_BAR_CLASSES;
			iccex.dwSize = sizeof(INITCOMMONCONTROLSEX);
			InitCommonControlsEx(&iccex);
		}
		//CREATE A TOOLTIP WINDOW
		m_hTipWnd = CreateWindowEx(WS_EX_TOPMOST,TOOLTIPS_CLASS,NULL,WS_POPUP|TTS_ALWAYSTIP,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,CW_USEDEFAULT,hParent,NULL,NULL,NULL);
		if(!m_hTipWnd)
			return FALSE;

		SetWindowPos(m_hTipWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE|SWP_NOACTIVATE);
		SendMessage(m_hTipWnd,TTM_SETMAXTIPWIDTH,0,240);
		return TRUE;
	}

	void CBasicSimpleToolTip::Destroy()
	{
		if(m_hTipWnd)
		{
			DestroyWindow(m_hTipWnd);
			m_hTipWnd = NULL;
		}
	}

	void CBasicSimpleToolTip::SetTipText( LPCTSTR lpszText,HWND hWnd,RECT& rc,void* pCurrentHolder )
	{
		if(!m_hTipWnd)
			return;

		TOOLINFO ti;
		memset(&ti,0,sizeof(TOOLINFO));
		ti.cbSize = sizeof(TOOLINFO) - 2*sizeof(void*);

		if((m_hFakeParent && m_hFakeParent != hWnd) || (m_pCurrentHolder && m_pCurrentHolder != pCurrentHolder))
		{
			//need to update the tooltip
			ti.hwnd = m_hFakeParent;
			ti.uId = 0;
			SendMessage(m_hTipWnd,TTM_DELTOOL, 0,(LPARAM)(LPTOOLINFO)&ti);
		}
		m_hFakeParent = hWnd;
		m_pCurrentHolder = pCurrentHolder;

		ti.uFlags = TTF_SUBCLASS;
		ti.hwnd = m_hFakeParent;
		ti.hinst = NULL;
		ti.uId = 0;
		ti.lpszText = (LPTSTR)lpszText;

		//ToolTip control will cover the whole window
		ti.rect.left = rc.left;
		ti.rect.top = rc.top;
		ti.rect.right = rc.right;
		ti.rect.bottom = rc.bottom;

		//SEND AN ADDTOOL MESSAGE TO THE TOOLTIP CONTROL WINDOW 
		SendMessage(m_hTipWnd,TTM_ADDTOOL,0,(LPARAM)(LPTOOLINFO)&ti);
		//SetWindowPos(m_hTipWnd,HWND_TOPMOST,0,0,0,0,SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);
	}

	void CBasicSimpleToolTip::SetTipWidth( int nWidth )
	{
		if(m_hTipWnd)
			SendMessage(m_hTipWnd,TTM_SETMAXTIPWIDTH,0,nWidth);
	}


	void CBasicSimpleToolTip::ClearTip()
	{
		TOOLINFO ti;
		memset(&ti,0,sizeof(TOOLINFO));
		ti.cbSize = sizeof(TOOLINFO) - 2*sizeof(void*);

		if(m_hTipWnd && m_hFakeParent)
		{
			ti.hwnd = m_hFakeParent;
			ti.uId = 0;
			SendMessage(m_hTipWnd,TTM_DELTOOL, 0, (LPARAM)(LPTOOLINFO)&ti);
		}
		m_pCurrentHolder = NULL;
	}

	void* CBasicSimpleToolTip::GetCurrentHolder()
	{
		return m_pCurrentHolder;
	}
}
